from __future__ import with_statement
import traceback, socket, sys, plugin

_version = '3.0 Stable'

class IRC:
	def __init__(self, host, port=6667):
		self._version = '3.0 Stable'
		self.host = host
		self.port = port
		self._sock = socket.socket()
		self._read = self._sock.makefile('rb')
		self.admins = ['keiouu']

	def __enter__(self):
		self._sock.connect((self.host, self.port))

	def __exit__(self, type, value, trace):
		self.quit('bye!')
		self._sock.close()

	def __getattr__(self, name):
		def fn(*args):
			if not args: args = ['']
			self._sock.send('%s %s :%s\r\n' % (name.upper(), ' '.join(args[:-1]), args[-1]))
		return fn

	def nick(self, nick):
		self.nick = nick
		self._sock.send('NICK %s\r\n' % nick)

	def add_admin(self, name):
		self.admins.push(name)

	def reply(self, to, msg):
		self.privmsg(to['channel'], to['sender']['name'] + ': ' + msg)

	@property
	def messages(self):
		while True:
			str = self._read.readline().strip()
			if not str: break
			if str.split()[0].lower() == 'ping':
				self.pong()
				continue
			meta, _, data = str[1:].partition(':')
			sender, type, chan = meta.split(' ', 2)
			sender_name, _, sender_host = sender.partition('!')
			sender = {'name': sender_name, 'host': sender_host,
			          'admin': (sender_name in self.admins)}
			if type == 'JOIN':
				chan = data
				data = ""
			yield {'sender': sender, 'type': type.lower(), 'channel': chan.rstrip(), 'data': data}

def _read_config():
	sections = {}
	curr_sec = ''
	f = open('config', 'r')
	for line in f.readlines():
		if len(line) <= 0: continue
		if line.startswith('['):
			name = line.rstrip()[1:-1]
			if name not in sections:
				sections[name] = []
			curr_sec = name
		else:
			l = line.rstrip()
			if '=' in l:
				name, _, value = l.partition('=')
				sections[curr_sec].append((name, value))
			elif curr_sec != '':
				sections[curr_sec].append(line.rstrip())
	return sections
	

if __name__ == '__main__':	
	sections = _read_config()
	host = sections['servers'][0]
	chans = sections['channels']
	nick = sections['core'][0][1]

	irc = IRC(host)
	with irc:
		irc.nick(nick)
		irc.user(nick, host, host, nick)
		plugin._plugin.irc = irc
		import plugins
		from plugins import *
		mods = Core()
		mods._onLoad()
		for chan in chans: irc.join(chan)
		for msg in irc.messages:
			if msg['data'] == '.restart' and msg['sender']['admin']:
				try:
					irc.reply(msg, 'Restarting modules')
					mods._onUnload()
					reload(plugin)
					import plugin
					plugin._plugin.irc = irc
					reload(plugins)
					import plugins
					from plugins import *
					mods = Core()
					mods._onReload()
				except: traceback.print_exc(file=sys.stdout)
			else:
				mods._handle(msg)
